package com.ittx.dzt.meituan.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.ittx.dzt.edi.constant.PlatformMessageConstant;
import com.ittx.dzt.edi.dto.OrderGetDTO;
import com.ittx.dzt.edi.dto.PlatformApiParamDTO;
import com.ittx.dzt.edi.dto.StoreConfigDTO;
import com.ittx.dzt.edi.vo.ResponseMessageVO;
import com.ittx.dzt.meituan.constant.MeituanApiConstant;
import com.ittx.dzt.meituan.handler.AbstractBaseMeituanApiHandler;
import com.ittx.dzt.sys.response.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.Consumer;

/**
 * 根据销售单号号下载售后单
 * <p>
 * cy.returnOrder.download.byOrderId
 * /api/v1/gw/order/batchGetRefundInfo(批量查询订单退款信息)  https://tscc.meituan.com/home/doc/bulkPurchasing/510
 * </p>
 *
 * @author gywang
 * @since 2024-08-01
 */
@Slf4j
@Service
public class MeituanReturnOrderDownloadBySourceOrderCodeService extends AbstractBaseMeituanApiHandler<OrderGetDTO> {

    /**
     * 每次查询最大数量
     */
    private static final int MAX_SIZE = 10;

    @Override
    public String getMeituanMethod() {
        return MeituanApiConstant.RETURN_BATCH_GET;
    }

    @Override
    public String getHttpMethod() {
        return MeituanApiConstant.ApiHttpMethod.POST;
    }

    @Override
    public String getLocalApiMethod() {
        return open.constant.PlatformApiConstant.InboundInterface.RETURNORDER_DOWNLOAD_BY_ORDERID;
    }

    @Override
    public Result<?> doProcess(PlatformApiParamDTO platformApiParamDTO, OrderGetDTO orderGetDTO) {
        // 销售单id
        List<List<String>> subs = CollUtil.split(Arrays.asList(StringUtils.split(orderGetDTO.getOrderId(), ",")), MAX_SIZE);
        List<Object> list = new ArrayList<>();
        for (List<String> sub : subs) {
            Result<?> result = this.getRefundById(platformApiParamDTO, sub);
            if (!result.isSuccess()) {
                return result;
            }
            List<Map<String, Object>> resultData = (List<Map<String, Object>>) result.getData();
            if (CollUtil.isNotEmpty(resultData)) {
                // 同步返回
                if (orderGetDTO.getIsAsync() == 0) {
                    list.addAll(resultData);
                } else {
                    for (Map<String, Object> rf : resultData) {
                        platformApiParamDTO.setPlatformIdentifierTag(rf.get("refund_id").toString());
                        result = this.sendRequestToPlatform(platformApiParamDTO, resultData, true);
                        if (!result.isSuccess()) {
                            return result;
                        }
                    }

                }
            }

        }
        // 同步返回
        if (orderGetDTO.getIsAsync() == 0) {
            return Result.success().addData(list).addMsg(platformApiParamDTO.getStoreConfig().getChainUniqueCode());
        }
        return Result.success();
    }


    /**
     * 根据id获取售后单
     *
     * @param platformApiParamDTO 平台参数
     * @param ids                 订单id
     * @return
     */
    public Result<?> getRefundById(PlatformApiParamDTO platformApiParamDTO, List<String> ids) {

        return this.getRefundBySDK(platformApiParamDTO, ids);
    }

    /**
     * 执行api请求sdk
     *
     * @param platformApiParamDTO 平台参数
     * @param ids                 订单id
     * @return 请求结果 resultMap.get(DATA_FIELD)
     */
    public Result<?> getRefundBySDK(PlatformApiParamDTO platformApiParamDTO, List<String> ids) {
        Map<String, String> params = new HashMap<>();
        // 订单Id
        params.put("order_view_ids", StringUtils.join(ids, ","));
        params.put("poi_id", getPoIId(platformApiParamDTO));
        StoreConfigDTO storeConfig = platformApiParamDTO.getStoreConfig();
        String requestId = platformApiParamDTO.getRequestId();
        Result<?> result = this.executeMeituanApi(storeConfig, params, requestId);
        if (!result.isSuccess()) {
            return result;
        }
        Map<String, Object> resultMap = (Map<String, Object>) result.getData();
        Map<String, Object> refundObj = (Map<String, Object>) resultMap.get(DATA_FIELD);
        if (refundObj == null || CollUtil.isEmpty((Collection<?>) refundObj.get("refund_order_data_list"))) {
            String msg = StrUtil.format(PlatformMessageConstant.MSG_PLAT_0009_MSG, requestId, StringUtils.join(ids, ","));
            log.error(msg);
            return Result.error(new ResponseMessageVO(PlatformMessageConstant.MSG_PLAT_0009, msg));
        }
        List<Map<String, Object>> refund_order_data_list = (List<Map<String, Object>>) refundObj.get("refund_order_data_list");
        List<Map<String, Object>> refunds = new ArrayList<>();
        for (Map<String, Object> rdata : refund_order_data_list) {
            List<Map<String, Object>> refund_record_list = (List<Map<String, Object>>) rdata.get("refund_record_list");
            if (CollUtil.isNotEmpty(refund_record_list)) {
                refund_record_list.forEach(new Consumer<Map<String, Object>>() {
                    @Override
                    public void accept(Map<String, Object> stringObjectMap) {
                        stringObjectMap.put("order_view_id", rdata.get("order_view_id"));
                    }
                });
                refunds.addAll(refund_record_list);
            }

        }
        return Result.success().addData(refunds);

    }
}
